/*
* ECARX Technology Limited is the owner of the copyright and the trade secret of this software. 
* Without permission, no one has the right to obtain, disclose or use this software in any way.
*/

package com.ecarx.systemui.plugin.utils;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Global executor pools for the whole application.
 * <p>
 * Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind
 * webservice requests).
 */
public class AppExecutors {

    private final Executor mWorkThreadIO;

    private final MainThreadExecutor mMainThread;

    private static class Holder {
        private final static AppExecutors INSTANCE = new AppExecutors();
    }

    public static AppExecutors getInstance() {
        return Holder.INSTANCE;
    }

    private AppExecutors( Executor workThreadIO, MainThreadExecutor mainThread) {
        this.mWorkThreadIO = workThreadIO;
        this.mMainThread = mainThread;
    }

    private AppExecutors() {
        this(Executors.newFixedThreadPool(6),
                new MainThreadExecutor());
    }



    public Executor workThreadIO() {
        return mWorkThreadIO;
    }

    public MainThreadExecutor mainThread() {
        return mMainThread;
    }

    public static class MainThreadExecutor implements Executor {
        private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

        public void delayExecute(long delay,@NonNull Runnable command) {
            mainThreadHandler.postDelayed(() -> execute(command), delay);
        }

        @Override
        public void execute(@NonNull Runnable command) {
            mainThreadHandler.post(command);
        }
    }
}
